package cn.jiedh.app.meiweidk.mine;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.ActionSheet;
import cn.jiedh.app.meiweidk.Utils.UI.CommonListItemView;
import cn.jiedh.app.meiweidk.Utils.UI.CustomItemLayout;
import cn.jiedh.app.meiweidk.Utils.event.EventScreen;
import cn.jiedh.app.meiweidk.Utils.event.EventUtils;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.FileHelper;
import cn.jiedh.app.meiweidk.Utils.tool.IDCard;
import cn.jiedh.app.meiweidk.Utils.tool.LoadUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.network.GlideCircleTransform;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * @name：
 * @author： liuyun
 * @phone： 15723310658
 * @createTime： 2017/12/11
 * @modifyTime： 2017/12/11
 * @explain：说明
 */


public class PersonalDataActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    private static final String TAG = PersonalDataActivity.class.getName();
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;

    @BindView(R.id.user_face_iv)
    ImageView userFaceIv;
    @BindView(R.id.nickname_civ)
    TextView nicknameCiv;


    @BindView(R.id.personal_phone)
    TextView personal_phone;//电话

    private OptionsPickerView valuesPickerView;



    @BindView(R.id.data_lin)
    LinearLayout data_lin;
    @BindView(R.id.notdata_lin)
    LinearLayout notdata_lin;


    @BindView(R.id.name_tv)
    TextView name_tv;
    @BindView(R.id.city_tv)
    TextView city_tv;
    @BindView(R.id.idcard_tv)
    TextView idcard_tv;

    @BindView(R.id.name_cil)
    CustomItemLayout name_cil;
    @BindView(R.id.idcard_cil)
    CustomItemLayout idcard_cil;
    @BindView(R.id.marry_cil)
    CustomItemLayout marry_cil;
    @BindView(R.id.monthlyIncome_cil)
    CustomItemLayout monthlyIncome_cil;
    @BindView(R.id.jobtype_cil)
    CustomItemLayout jobtype_cil;
    @BindView(R.id.payoff_cil)
    CustomItemLayout payoff_cil;
    @BindView(R.id.city_cil)
    CustomItemLayout city_cil;
    @BindView(R.id.credit_cil)
    CustomItemLayout credit_cil;
    @BindView(R.id.car_cil)
    CustomItemLayout car_cil;
    @BindView(R.id.house_cil)
    CustomItemLayout house_cil;
    @BindView(R.id.fund_cil)
    CustomItemLayout fund_cil;
    @BindView(R.id.social_cil)
    CustomItemLayout social_cil;
    @BindView(R.id.guarantee_cil)
    CustomItemLayout guarantee_cil;
    @BindView(R.id.creditCase_cil)
    CustomItemLayout creditCase_cil;
    @BindView(R.id.weilidai_cil)
    CustomItemLayout weilidai_cil;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_personal_data;
    }

    @Override
    protected void initView(View view) {
        setTitle("我的资料");
    }

    @Override
    protected void initData() {

    }

    /**
     * 获取用户信息
     */
    private void getPersonData() {
        Map<String, Object> args = new HashMap<>();
        args.put("phone", SPUtils.getPhone());
        showLoadingDialog();
        request(this, UrlUtils.GET_PERSONAL_INFO, args, true, new ResponseSuccess<PersonInfo>() {
            @Override
            public void onRequestSucceed(BaseResponse<PersonInfo> response) {
                dismissLoadingDialog();
                PersonInfo infor = response.getData();

                String maskNumber = infor.getPhone().substring(0, 3) + "****" + infor.getPhone().substring(7, infor.getPhone().length());

                personal_phone.setText("电话 : "+maskNumber);
                nicknameCiv.setText("用户 : "+infor.getUsername());
                if (!TextUtils.isEmpty(infor.getUserImgUrl())) {
                    LoadUtils.loadImage(PersonalDataActivity.this,infor.getUserImgUrl(),userFaceIv);
//                    Glide.with(PersonalDataActivity.this).load(infor.getUserImgUrl()).error(R.mipmap.app_icon).dontAnimate().transform(new GlideCircleTransform(PersonalDataActivity.this)).into(userFaceIv);
                }else{
                    Glide.with(PersonalDataActivity.this).load(R.mipmap.app_icon).dontAnimate().transform(new GlideCircleTransform(PersonalDataActivity.this)).into(userFaceIv);
                }
                if (response.isSuccess()) {
                    notdata_lin.setVisibility(View.GONE);
                    data_lin.setVisibility(View.VISIBLE);
                    initPersonData(infor);

                    SPUtils.saveUserData(infor);

                }else{
                    notdata_lin.setVisibility(View.VISIBLE);
                    data_lin.setVisibility(View.GONE);
                }
            }
        }, (error, msg) -> {
            dismissLoadingDialog();
            T.showShortToast(msg);
        });
    }




    /**
     * 设置用户信息
     */
    private void initPersonData(PersonInfo info){

        name_cil.setValue(info.getUsername());
        idcard_cil.setValue(info.getIdCard().replaceAll("(\\d{4})\\d{10}(\\d{4})","$1****$2"));
        marry_cil.setValue(info.getMaritalStatus());
        monthlyIncome_cil.setValue(info.getMonthlyIncome());
        jobtype_cil.setValue(info.getJobType());
        payoff_cil.setValue(info.getPayoff());
        city_cil.setValue(info.getCityLive());
        credit_cil.setValue(info.getCredit());
        car_cil.setValue(info.getCar());
        house_cil.setValue(info.getHouse());
        fund_cil.setValue(info.getFund());
        social_cil.setValue(info.getSocial());
        guarantee_cil.setValue(info.getGuarantee());
        creditCase_cil.setValue(info.getCreditCase());
        weilidai_cil.setValue(info.getWeilidai());

        name_tv.setText(info.getUsername());
        city_tv.setText(info.getCityLive());
        idcard_tv.setText(info.getIdCard().replaceAll("(\\d{4})\\d{10}(\\d{4})","$1****$2"));


    }



    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        getPersonData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @OnClick({R.id.exchange_head, R.id.nickname_civ,
           R.id.edit_content})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.exchange_head:
                List<String> items = new ArrayList<>();
                items.add("拍照");
                items.add("相册");
                ActionSheet as = new ActionSheet(this, null, items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                selectFace(true);
                                break;
                            case 1:
                                selectFace(false);
                                break;
                        }
                    }
                });
                as.show();
                break;
            case R.id.edit_content://去填写资料
                ActivityUtil.next(this,AuthenActivity.class);
                break;
        }
    }

    private void selectFace(boolean isTake) {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        //设置参数
        configCompress(takePhoto);
        configTakePhotoOption(takePhoto);
        if (isTake) {
            takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
//            takePhoto.onPickFromCapture(imageUri);
        } else {
            takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());

        }
    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(false);
        builder.setCorrectImage(false);
        takePhoto.setTakePhotoOptions(builder.create());

    }

    private void configCompress(TakePhoto takePhoto) {
        int width = 800;
        int height = 800;
        boolean showProgressBar = true;
        boolean enableRawFile = true;
        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(102400)
                .setMaxPixel(width >= height ? width : height)
                .enableReserveRaw(enableRawFile)
                .create();
        takePhoto.onEnableCompress(config, showProgressBar);


    }

    private CropOptions getCropOptions() {
        int height = 800;
        int width = 800;
        boolean withWonCrop = false;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
//            builder.setOutputX(width).setOutputY(height);
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }

    private void selectValue(CommonListItemView civ, String... values) {

        if (values == null || values.length == 0) {
            return;
        }
        if (valuesPickerView != null && valuesPickerView.isShowing()) {
            valuesPickerView.dismiss();
        }
        valuesPickerView = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
            civ.setRightText(values[options1]);
        }).setOutSideCancelable(false)
                .setDividerColor(R.color.hint3_text_color)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        valuesPickerView.setPicker(Arrays.asList(values));
        valuesPickerView.show();
    }

    @Override
    public void takeSuccess(TResult result) {
        Log.i(TAG, "takeSuccess：" + result.getImage().getCompressPath());
        Map<String, Object> args = new HashMap<>();
        args.put("phone", SPUtils.getPhone());
        String imageBase64=FileHelper.getImageStr(result.getImage().getCompressPath());
        args.put("imgBase64",imageBase64);
        showLoadingDialog();
        request(this, UrlUtils.UPLOADE_USER_IMAGE, args, true, new ResponseSuccess<UserLogo>() {
            @Override
            public void onRequestSucceed(BaseResponse<UserLogo> response) {
                dismissLoadingDialog();
                if (response.isSuccess()) {
                    EventScreen eventScreen = new EventScreen("pic", response.getData().getUserImgUrl());
                    EventUtils.getDefault().forward(eventScreen);
                    T.showShortToast("头像上传成功");
                    LoadUtils.loadImage(PersonalDataActivity.this,response.getData().getUserImgUrl(),userFaceIv);
                } else {
                    T.showShortToast(response.getMessage());
                }
            }
        }, (error, msg) -> {
            dismissLoadingDialog();
            T.showShortToast("头像上传失败");
        });
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(com.jph.takephoto.R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }
}
